<?php

namespace app\controller\adminapi\cloud;

use think\facade\Cache;
use app\common\services\Upgrade;
use hiduoke\services\CloudServer;
use app\common\model\system\Config;
use hiduoke\controller\BaseController;

/**
 * Notes: 云服务
 * Create by :  刘泓宾<514660094@qq.com>
 * Copyright :  copyright (c) 多客怪兽, www.dkyx.cc
 * Created on:  2025/8/6 03:09
 */
class Cloud extends BaseController
{
    /**
     * @var Upgrade
     */
    private Upgrade $upgrade;
    /**
     * @var false|mixed
     */
    private $version;
    /**
     * @var CloudServer
     */
    private CloudServer $cloud;

    protected $visit_type = 'admin';

    protected function initialize()
    {
        $this->cloud = new CloudServer();
        $this->upgrade = new  Upgrade();
        $this->version = $this->upgrade->getVersion();
    }

    /**
     * 获取站点信息
     * Create by :  刘泓宾<514660094@qq.com>
     * @return \think\response\Json
     */
    public function getSiteMsg()
    {
        $res = $this->cloud->getSite();
        if ($res['code'] == 0) {
            $data = $res['data'];
            $data['m_token'] = hide_str($data['token'], 5, 5, 2, 8);
            $data['version'] = $this->version;
            (new CloudServer())->updateSite();
            return $this->success('ok', $data);
        } else {
            $cloud = Config::get("cloud");
            return $this->error($res['msg'], $cloud);
        }
    }

    /**
     * 获取登录用户token
     * Create by :  刘泓宾<514660094@qq.com>
     * @return \think\response\Json
     */
    public function getTokenByLoginUser()
    {
        $account = input('account', '');
        $password = input('password', '');
        $res = $this->cloud->getTokenByLoginUser($account, $password);
        if ($res['code'] == 0) {
            return $this->success('ok', $res['data']);
        } else {
            return $this->error($res['msg']);
        }
    }

    /**
     * 获取站点信息
     * Create by :  刘泓宾<514660094@qq.com>
     * @return \think\response\Json
     */
    public function getSiteMsgByLoginUser()
    {
        $account = input('account', '');
        $password = input('password', '');
        $res = $this->cloud->getSiteMsgByLoginUser($account, $password);
        // TODO 获取后要绑定
        if ($res['code'] == 0) {
            $cloud = (new Config())->where(['key' => 'cloud'])->findOrEmpty();
            $data = $res['data'];
            $cloud->key = 'cloud';
            $cloud->value = array(
                'site_id' => $data['id'],
                'token'   => $data['token'],
                'version' => $data['version'],
                'domain'  => $data['domain'],
            );
            $cloud->save();
            return $this->success('ok', $data);
        } else {
            return $this->error($res['msg']);
        }
    }

    /**
     * 获取主程序更新信息
     * Create by :  刘泓宾<514660094@qq.com>
     * @return \think\response\Json
     */
    public function getUpdateMsg()
    {
        $res = $this->cloud->getUpdateProgram($this->version['version']);
        $data = array('list' => []);
        $data['version'] = $this->version;
        if ($res['code'] == 0) {
            $data['list'] = $res['data'];
            $data['version']['new_version'] = end($data['list']);
        }
        return $this->success("ok", $data);
    }

    /**
     * 更新主程序
     * Create by :  刘泓宾<514660094@qq.com>
     * @return \think\response\Json
     */
    public function upgrade()
    {
        $stime = microtime(true);
        //更新目录
        $local_up_dir = $this->app->getRuntimePath() . "upgrade/";
        //临时目录
        $local_up_dir_tmp = $local_up_dir . 'tmp/';
        if (!is_dir($local_up_dir_tmp)) {
            mkdir(iconv("UTF-8", "GBK", $local_up_dir_tmp), 0777, true);
        }
        // 比对版本
        $local = $this->upgrade->getVersion();
        if (!$local) {
            return $this->error("本地版本文件异常");
        }
        // 获取版本
        $program_res = $this->cloud->getUpdateProgram($local['version']);

        if ($program_res['code'] != 0) {
            return $this->error($program_res['msg']);
        }
        $program = $program_res['data'];
        var_dump(1);
exit();
        // 下载文件 到 临时目录
        if (is_array($program)) {
            foreach ($program as $key => $value) {
                //下载
                $back = down_file($value['down_file'], $local_up_dir_tmp);
                if (empty($back)) {
                    return $this->error("升级安装包下载失败");
                } else {
                    //解压
                    $zip_res = deal_zip($back['save_path'], $local_up_dir_tmp);
                    if ($zip_res == 406) {
                        return $this->error("文件解压失败");
                    } else {
                        //数据库
                        $mysql_dir = $local_up_dir_tmp . $value['name'] . '/mysql/';
                        $sql_res = $this->upgrade->carry_sql($mysql_dir);
                        if ($sql_res === false) {
                            return $this->error("数据库写入失败");
                        } else {
                            //合并文件
                            $program_dir = $local_up_dir_tmp . $value['name'] . '/program/';
                            $file_up_res = $this->upgrade->copy_merge($program_dir, $this->app->getRootPath());
                            if ($file_up_res === false) {
                                return $this->error("合并文件失败");
                            } else {
                                //修改版号
                                $new_version = json_encode([
                                    'name'             => $value['name'],
                                    'updatetime'       => time(),
                                    'version'          => $value['version'],
                                    'version_detailed' => $value['version_detailed'],
                                ]);
                                $write_res = file_put_contents($local_up_dir . 'version', $new_version);
                                $cloud = (new Config())->getValueByKey('cloud');
                                $cloud['version'] = $value['version'];
                                (new Config())->setValueByKey($cloud, 'cloud');
                                if (!$write_res) {
                                    return $this->error("修改本地版本失败");
                                } else {
                                    //删除临时文件
                                    $this->upgrade->deldir($local_up_dir_tmp);
                                }
                            }
                        }
                    }
                }
            }
        }
        $etime = microtime(true);
        $timed = round(floatval($etime - $stime), 2);   //计算差值
        (new CloudServer())->updateSite();
        Cache::clear();
        return $this->success("升级成功,耗时：" . $timed . '秒');
    }

    /**
     * 获取站点应用信息
     * Create by :  刘泓宾<514660094@qq.com>
     * @return \think\response\Json
     */
    public function addon()
    {
        $name = $this->request->post('name', '');
        $res = $this->cloud->getAddon($name);
        if ($res['code'] == 0) {
            $data = $res['data'];
            $data['detail_content'] = htmlspecialchars_decode(htmlspecialchars_decode($data['detail_content']));
            return $this->success('', $data);
        } else {
            return $this->error($res['msg']);
        }
    }

    /**
     * 应用下载
     * Create by :  刘泓宾<514660094@qq.com>
     * @return \think\response\Json
     */
    public function addon_down()
    {
        $stime = microtime(true);
        //更新目录
        $local_up_dir = $this->app->getRuntimePath() . "addon/";
        //临时目录
        $local_up_dir_tmp = $local_up_dir . 'tmp';
        if (!is_dir($local_up_dir_tmp)) {
            mkdir(iconv("UTF-8", "GBK", $local_up_dir_tmp), 0777, true);
        }
        $name = $this->request->post('name', '');
        $res = $this->cloud->getAddon($name);
        if ($res['code'] != 0) {
            return $this->error($res['msg']);
        }
        $down_file = $res['data']['new_version_file'];
        $back = down_file($down_file, $local_up_dir_tmp);
        if (empty($back)) {
            return $this->error("升级安装包下载失败");
        } else {
            $zip_res = deal_zip($back['save_path'], $local_up_dir_tmp);
            if ($zip_res == 406) {
                return $this->error("文件解压失败");
            } else {
                $addon_dir = $local_up_dir_tmp . '/' . $name . '/';
                $file_up_res = $this->upgrade->copy_merge($addon_dir, $this->app->getRootPath() . '/addons/' . $name);
                if ($file_up_res === false) {
                    return $this->error("合并文件失败");
                } else {
                    //删除文件
                    $this->upgrade->deldir($local_up_dir_tmp);
                }
            }
        }
        $etime = microtime(true);
        $timed = round(floatval($etime - $stime), 2);   //计算差值
        return $this->success("下载成功,耗时：" . $timed . '秒');
    }

    /**
     * 获取应用更新内容
     * @return \think\response\Json
     */
    public function getUpdateAddon()
    {
        $name = $this->request->post('name', '');
        $res = $this->cloud->getAddonUpdateMsg($name);
        if ($res['code'] == 0) {
            $data = $res['data'];
            $data['content'] = htmlspecialchars_decode(htmlspecialchars_decode($data['content']));
            return $this->success('', $data);
        } else {
            return $this->error($res['msg']);
        }
    }
}
